package com.javaee.term.controller;

import com.javaee.term.constant.LoginCookieConstant;
import com.javaee.term.model.SaleMan;
import com.javaee.term.service.LoginRoleService;
import com.javaee.term.service.SalemanService;
import com.javaee.term.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * author 陈伯瑞
 * date 2019/12/23 0023 14:25
 * version 1.0
 **/
@Controller
@RequestMapping("/seller")
public class LoginController {
    @Autowired
    LoginRoleService loginRoleService;
   @Autowired
    SalemanService salemanService;
    @GetMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("index/index");
    }

    @ModelAttribute
    @GetMapping("/login/role")
    public ModelAndView login(@RequestParam(value = "adminName", required = false) String adminName,
                              @RequestParam(value = "password", required = false) String password,
                              HttpServletResponse response,
                              Map<String, Object> map,
                              HttpSession session) {
        String role;
        role=loginRoleService.findTheRoleOfAdmin(adminName,password);
        if(!role.equals("noneRole"))
            CookieUtil.set(response, LoginCookieConstant.TOKEN, "token",LoginCookieConstant.EXPIRE);
        if(role.equals("saleAdmin"))
            return  new ModelAndView("redirect:/seller/contact/list");
        if(role.equals("saleMan")) {
            //假如登录的是销售员记录id，以便数据统计个人业绩；
            SaleMan saleManByAccount = salemanService.findByAccount(adminName);
            session.setAttribute("manId", saleManByAccount.getManId());
            return  new ModelAndView("redirect:/seller/saleCondition/list",map);
        }
        if(role.equals("stockMan")) return  new ModelAndView("redirect:/seller/sendProduct/list");
        else return  new ModelAndView("index/index");
    }
    @GetMapping("/login/out")
    public ModelAndView loginOut(HttpServletResponse response) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //查询cookie
        Cookie cookie = CookieUtil.get(request, LoginCookieConstant.TOKEN);
        cookie.setPath("/");
        cookie.setMaxAge(LoginCookieConstant.UNEXPIRED);
        cookie.setValue("untoken");
        response.addCookie(cookie);
        return new ModelAndView("index/index");
    }
}
